<?php
namespace App\Http\Controllers\Admin;

use App\Models\BbsHots;
use Illuminate\Http\Request;
use App\Models\BbsQuestion;
/**
 *
 * @author Joker
 *        
 */
class BbsTopController extends BaseController
{
    
    public function index()
    {
        if(!$this->user->can('viewBbsQuestion')) abort(405);
        
        $hotList = BbsHots::with(['getQuestion'=>function ($query){
            $query->where('deleted_at','=',null);
        }])->orderBy('sort','DESC')->orderBy('created_at','DESC')->paginate(20);
        
        return view('admin.bbs.hots.index')->with('hotlist',$hotList);
    }
    
    public function create()
    {
        if(!$this->user->can('viewBbsQuestion')) abort(405);
        
         $questions = BbsQuestion::orderBy('is_hot','DESC')->orderBy('created_at','DESC')->get();
         return view('admin.bbs.hots.details')->with('questions',$questions);
    }
    
    public function edit($id)
    {
        if(!$this->user->can('viewBbsQuestion')) abort(405);
        
        $hots = BbsHots::find($id);
        if(empty($hots))
        {
           abort(404); 
        }
        $questions = BbsQuestion::orderBy('is_hot','DESC')->orderBy('created_at','DESC')->get();
        return view('admin.bbs.hots.details')->with('questions',$questions)->with('result',$hots);
    }
    
    public function store(Request $req)
    {
        if(!$this->user->can('viewBbsQuestion')) return $this->formatJson('error',$this->permerror);
        
        $data = $req->only('question_id','thumb','sort','intro');
        $hots = BbsHots::find($data['question_id']);
        if(!empty($hots))
        {
            $hots->thumb = $data['thumb'];
            $hots->sort = $data['sort'];
            $hots->intro = $data['intro'];
            $hots->save();
        }
        else
        {
            $hots = BbsHots::firstOrCreate($data);
        }
        return $this->formatJson('success','成功',$hots,'/admin/bbs/top');
    }
    
    public function destroy($id)
    {
        if(!$this->user->can('viewBbsQuestion')) return $this->formatJson('error',$this->permerror);
        
        $hots = BbsHots::find($id);
        if(empty($hots))
        {
            return $this->formatJson('error',$this->permerror);
        }
        
        $hots->delete();
        return $this->formatJson('success','删除成功！');
        
    }
}